package com.joint.action.com;

import com.joint.action.BaseAction;
import com.joint.action.demo.DemoImageHandler;
import com.joint.action.demo.DemoLogHandler;
import com.joint.action.demo.DemoTextHandler;
import me.chanjar.weixin.common.util.StringUtils;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Administrator on 2015/2/10.
 */
@ParentPackage("com")
public class IndexAction extends BaseAction {

    private static String AppId = "wx132a951bca890c86";
    private static String AppSecret = "b9c09afc67dd2c52eb125b553cf24dfc";
    private static String Token = "xuheng1234567890";
    private static String EncodingAESKey = "kis9VVA7V7AczhdiHo4KO9mYvjAWOmdmf1YKhQAB7RH";

    protected static WxMpInMemoryConfigStorage config;
    protected static WxMpServiceImpl wxService;
    protected static WxMpMessageRouter wxMpMessageRouter;

    private static void initWeixin() {
        if (null == config){
            System.out.println("config is init");
            config = new WxMpInMemoryConfigStorage();
            config.setAppId(AppId); // 设置微信公众号的appid
            config.setSecret(AppSecret); // 设置微信公众号的app corpSecret
            config.setToken(Token); // 设置微信公众号的token
            config.setAesKey(EncodingAESKey);

            wxService = new WxMpServiceImpl();
            wxService.setWxMpConfigStorage(config);

            wxMpMessageRouter = new WxMpMessageRouter(wxService);

            WxMpMessageHandler logHandler = new DemoLogHandler();
            WxMpMessageHandler textHandler = new DemoTextHandler();
            WxMpMessageHandler imageHandler = new DemoImageHandler();
            wxMpMessageRouter
                    .rule().handler(logHandler).next()
                    .rule().async(false).content("哈哈").handler(textHandler).end()
                    .rule().async(false).content("图片").handler(imageHandler).end()
                    ;
        }
    }


    public String execute() throws IOException {
        initWeixin();
        System.out.println("initWeixin");

        HttpServletRequest request = getRequest();
        HttpServletResponse response = getResponse();

        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);

        String signature = request.getParameter("signature");
        String nonce = request.getParameter("nonce");
        String timestamp = request.getParameter("timestamp");

        if (!wxService.checkSignature(timestamp, nonce, signature)) {
            // 消息签名不正确，说明不是公众平台发过来的消息
            response.getWriter().println("非法请求");
            return null;
        }
        System.out.println("checkSignature");

        String echostr = request.getParameter("echostr");
        if (StringUtils.isNotBlank(echostr)) {
            // 说明是一个仅仅用来验证的请求，回显echostr
            response.getWriter().println(echostr);
            return null;
        }
        System.out.println("no echostr");

        String encryptType = StringUtils.isBlank(request.getParameter("encrypt_type")) ?
                "raw" :
                request.getParameter("encrypt_type");

        if ("raw".equals(encryptType)) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
            WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
            if (outMessage != null) {
                System.out.println("明文传输的消息:" + outMessage.toXml());
                response.getWriter().write(outMessage.toXml());
            }
            return null;
        }

        if ("aes".equals(encryptType)) {
            // 是aes加密的消息
            String msgSignature = request.getParameter("msg_signature");
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(request.getInputStream(), config, timestamp, nonce, msgSignature);
            WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
            response.getWriter().write(outMessage.toEncryptedXml(config));
            return null;
        }

        response.getWriter().println("不可识别的加密类型");
        return null;

    }

    public String center(){
        return "center";
    }
}
